import { createRouter, createWebHashHistory } from "vue-router";
import { getmenu } from "../api/menu";
import { Igetrole } from "../utils/getroles";
import storage from "../utils/storage";
import { buildSubtreeFromLeaves } from "../utils/lbtree";
import { staticRoutes } from "../utils/constData";
import { createApiRouter } from "../utils/createrouterapi";
import { useMenuStore } from "../store";
const router = createRouter({
  history: createWebHashHistory(),
  routes: [...staticRoutes],
});
let flag = false;
router.beforeEach(async (to, _from, next) => {
  const { menu, role } = useMenuStore();

  if (!storage.get("token")) {
    if (to.path !== '/login') {
      return next(`/login?redirect=${to.fullPath}`);
    }
    return next();
  }


    let res = await getmenu();
    let { pagerole: ids, btnrole } = (await Igetrole() as any);
    role.setv([...new Set(btnrole)]);

    const menuTree = buildSubtreeFromLeaves(res.data, ids);
    let ff = createApiRouter(menuTree) as any;
    menu.setv(ff);

    router.clearRoutes();
    let item = staticRoutes.filter((es) => es.name == "layout")[0] as any;
    item.children = [...item.children, ...ff];

    for (let e of staticRoutes) {
      router.addRoute(e);
    }

    if (to.path === '/login') {
      return next('/layout');
    }

    if (!flag) {
      flag = true;
      return next({ ...to, replace: true });
    }

    next();

 
});

export default router;
